import Metadata from '@/lib/metadata';
import { authMiddleware } from '@/lib/api';
import { cookies } from 'next/headers';
import { queryPath } from '@/services/api';
import RegisterPage from '@/app/[locale]/register/register';
import ResetPage from '@/app/[locale]/reset/reset';
import { Metadata as MetadataNext } from 'next';
import { customException, getMetadata } from '@/lib/tool';
import RegisterH5Page from '@/app/[locale]/register/h5';
import type { IPath } from '@/interfaces';
import { createTranslator } from 'next-intl';
import { getMessages } from '@/lib/dictionaries';

export async function generateMetadata({
  params: { locale },
}: {
  params: {
    locale: string;
  };
}): Promise<MetadataNext> {
  const t = createTranslator(await getMessages(locale));
  return getMetadata({ title: t('RegisterPage.userRegistration') });
}

export default async function Page({
  params = {},
  searchParams = {},
}: {
  params: {};
  searchParams: {
    v?: 'h5';
  };
}) {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/register',
      },
    });

    const responses = await Promise.all([req1]);
    const resp1 = await ((await responses[0]) as Response).json();
    const data = resp1.data as IPath;
    if (data.siteConfig && data.siteConfig.disableRegistration) {
      return <ResetPage error={customException(400, '暂未开放注册')} />;
    }

    const metadata = new Metadata();
    metadata.set('page', ['/paths', '/register'], data);
    return searchParams.v === 'h5' ? (
      <RegisterH5Page metadata={metadata.toString()} />
    ) : (
      <RegisterPage metadata={metadata.toString()} />
    );
  } catch (e) {
    return <ResetPage error={e} />;
  }
}
